package com.pubinfo.passbook.common.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.pubinfo.passbook.common.entity.TContractBase;
import com.pubinfo.passbook.common.entity.TRabbitmqPerson;
import com.pubinfo.passbook.common.mapper.TRabbitmqOrgConvertMapper;
import com.pubinfo.passbook.common.mapper.TRabbitmqPersonMapper;
import com.pubinfo.passbook.common.mapper.TSystemRoleMapper;
import com.pubinfo.passbook.common.model.bo.Excel;
import com.pubinfo.passbook.common.model.bo.contract.ContractExcel;
import com.pubinfo.passbook.common.service.contract.TContractBaseService;
import com.pubinfo.passbook.common.service.master.TSubsidiaryInfoService;
import com.pubinfo.passbook.common.service.master.TSubsidiaryPrivateKeyService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class ContractExcelDataListener extends AnalysisEventListener<ContractExcel> {
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 10000;
    List<ContractExcel> list = new ArrayList();
    
    private TRabbitmqPersonMapper tRabbitmqPersonMapper;
    
    private TSystemRoleMapper tSystemRoleMapper;
    
    private TRabbitmqOrgConvertMapper tRabbitmqOrgConvertMapper;
    private TContractBaseService baseService;
    
    public List<ContractExcel> getList() {
        return list;
    }
    
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private TSubsidiaryPrivateKeyService keyService;
    private TSubsidiaryInfoService infoService;
    
    public ContractExcelDataListener(TRabbitmqPersonMapper tRabbitmqPersonMapper, TSystemRoleMapper tSystemRoleMapper, TRabbitmqOrgConvertMapper tRabbitmqOrgConvertMapper, TContractBaseService baseService) {
        this.tSystemRoleMapper = tSystemRoleMapper;
        this.tRabbitmqPersonMapper = tRabbitmqPersonMapper;
        this.tRabbitmqOrgConvertMapper = tRabbitmqOrgConvertMapper;
        this.baseService = baseService;
    }
    
    public ContractExcelDataListener() {
        // 这里是demo，所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数
        //    uploadDAO = new TAutoInterfaceService();
    }
    
    /**
     * 加上存储数据库
     */
    @Transactional
    public void saveData() {
        List<TContractBase> baseList = new ArrayList<>();
        for (ContractExcel companyExcel : list) {
            List<TRabbitmqPerson> tRabbitmqPeople = new ArrayList<>();
            if (StringUtils.isNotBlank(companyExcel.getAcctName())) {
                tRabbitmqPeople = tRabbitmqPersonMapper.selectAcctByNameAndPhone(companyExcel.getAcctName(), null);
            }
            
            //如果不能在人员表找到，则跳过不处理。
            //如果该人员能在人员表中找到，
            //如果只有一个或多个 则查询权限表，看是否存在，如果存在则关联认领，不存在则不处理
            
            if (CollectionUtils.isNotEmpty(tRabbitmqPeople)) {
                String acct = tSystemRoleMapper.findCountRoleByAcct(tRabbitmqPeople.stream().map(TRabbitmqPerson::getAcct).collect(Collectors.toList()));
                if (StringUtils.isNotBlank(acct)) {
                    baseService.contractAdopt(acct, companyExcel.getContractCode());
                }
                
            }
            
        }
    }
    
    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }
    
    private Boolean checkObjIsNull(Excel interfaceImport) {
        for (Field f : interfaceImport.getClass().getDeclaredFields()) {
            f.setAccessible(true);
            try {
                if (f.get(interfaceImport) == null || "".equals(f.get(interfaceImport).toString())) { //判断字段是否为空，并且对象属性中的基本都会转为对象类型来判断
                    //  throw new ServiceException("请求参数不能为空");
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            
        }
        return true;
    }
    
    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(ContractExcel data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }
}
